#include "user.h"

namespace GlobalUser
{
	QVector <User> userList;
	QDir userDataDir;
	QFile userDataFile;
}

using namespace GlobalUser;

QVector <User> User::getUserList()
{
	return userList;
}

QString User::getName()
{
	return this->name;
}

QString User::getPasswd()
{
	return this->passwd;
}

int User::getRecord(int level)
{
	return record[level];
}

void User::setName(QString name)
{
	this->name = name;
}

void User::setPasswd(QString passwd)
{
	this->passwd = passwd;
}

void User::checkDataFile()
{
	//	检查用户数据文件和目录是否存在

	userDataDir.setPath("C:/ProgramData/Mine Sweeper/");
	userDataFile.setFileName("C:/ProgramData/Mine Sweeper/UserData.data");

	if (!userDataDir.exists())
	{
		userDataDir.mkdir("C:/ProgramData/Mine Sweeper/");
	}
	if (!userDataFile.exists())
	{
		userDataFile.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Append);
	}
	else { userDataFile.open(QIODevice::ReadWrite | QIODevice::Text); }
}

void User::readDataFile()
{
	//	从文件中读取用户数据存入用户列表

	checkDataFile();

	QTextStream stream(&userDataFile);

	for (int i = 0; !stream.atEnd(); i++)
	{
		static User userTemp;

		userTemp.index = stream.readLine().toInt();
		userTemp.name = stream.readLine();
		userTemp.passwd = stream.readLine();

		for (int level = EASY_LEVEL; level <= HIGH_LEVEL; level++)
		{
			userTemp.record[level] = stream.readLine().toInt();
		}
		userList.append(userTemp);
	}
	userDataFile.close();
}

void User::saveDataFile()
{
	//	将用户列表中的数据写入数据文件

	checkDataFile();

	QTextStream stream(&userDataFile);

	for (int i = 0; i < userList.size(); i++)
	{
		stream << userList[i].index << endl;
		stream << userList[i].name << endl;
		stream << userList[i].passwd << endl;

		for (int level = EASY_LEVEL; level <= HIGH_LEVEL; level++)
		{
			stream << userList[i].record[level] << endl;
		}
	}
	userDataFile.close();
}

bool User::login()
{
	for (int i = 0; i < userList.size(); i++)
	{
		if (name == userList[i].name && passwd == userList[i].passwd)
		{
			//	检查用户名和密码是否正确

			index = userList[i].index;

			for (int level = EASY_LEVEL; level <= HIGH_LEVEL; level++)
			{
				record[level] = userList[i].record[level];
			}
			return true;
		}
	}
	return false;
}

bool User::registry()
{
	for (int i = 0; i < userList.size(); i++)
	{
		if (name == userList[i].name)
		{
			//	检查用户名是否存在

			return false;
		}
	}
	index = userList.size();

	for (int level = EASY_LEVEL; level <= HIGH_LEVEL; level++)
	{
		record[level] = INT_MAX;
	}
	userList.append(*this);
	return true;
}

void User::addRecord(int time, int level)
{
	//	添加游戏数据记录

	if (time < record[level])
	{
		record[level] = time;
		userList[index].record[level] = time;
	}
}
